package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.enums.YesNoEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.MessReceive;
import com.ruoyi.system.service.IMessReceiveService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MessSendMapper;
import com.ruoyi.system.domain.MessSend;
import com.ruoyi.system.service.IMessSendService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发送消息Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class MessSendServiceImpl extends ServiceImpl<MessSendMapper, MessSend> implements IMessSendService {

    @Autowired
    private MessSendMapper messSendMapper;
    @Autowired
    private IMessReceiveService messReceiveService;

    @DataScope
    @Override
    public List<MessSend> selectList(MessSend messSend) {
        return messSendMapper.list(messSend);
    }

    @Transactional
    @Override
    public void addMessSend(MessSend messSend){
        //新增发送消息记录
        messSend.setIsSend(YesNoEnum.NO.getCode())
                .setIsRead(YesNoEnum.NO.getCode())
                .setIsDel(YesNoEnum.NO.getCode())
                .setCreateTime(new Date());
        if (messSend.getSendTime() == null){
            messSend.setSendTime(messSend.getCreateTime());
        }
        save(messSend);
        //批量新增接收消息记录
        String[] userIds = messSend.getReceiveUserId().split(",");
        if (ObjectUtils.isEmpty(userIds)) return;
        List<MessReceive> resultList = Arrays.stream(userIds).map(i -> {
            MessReceive messReceive = new MessReceive()
                    .setReceiveUserId(Long.valueOf(i))
                    .setSendId(messSend.getId())
                    .setIsDel(YesNoEnum.NO.getCode())
                    .setIsRead(YesNoEnum.NO.getCode());
            return messReceive;
        }).collect(Collectors.toList());
        messReceiveService.saveBatch(resultList);
        //发送WebSocket消息
    }

    @Override
    @DataScope
    public MessSend getDetail(MessSend messSend){
        messSend = messSendMapper.get(messSend);
        List<MessReceive> messReceiveList = messReceiveService.getListBySendId(messSend.getId());
        messSend.setMessReceiveList(messReceiveList);
        return messSend;
    }

}
